package cn.yx.common.mdc.thread;

import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * <p>MDC包装Callable，线程中可支持MDC上下文信息</p>
 *
 * @param <V>
 * @author Wgssmart
 */
public class MdcCallable<V> implements Callable<V> {

    private final Callable<V> callable;

    public MdcCallable(Callable<V> callable) {
        this.callable = callable;
    }

    @Override
    public V call() throws Exception {
        Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
        if (!copyOfContextMap.isEmpty()) {
            MDC.setContextMap(copyOfContextMap);
        }
        try {
            return callable.call();
        } finally {
            if (!copyOfContextMap.isEmpty()) {
                MDC.clear();
            }
        }

    }

}
